const Service = require('egg').Service
module.exports = class userService extends Service {
  async create({
    userName,
    workNumber,
    passwd,
    phone,
    userId,
    aroleid,
    type
  }) {
    let res = {};
    const {
      ctx,
      app,
      service
    } = this;
    try {
      let isRegister = await service.common.findOne({
        tableName: 'hd_admin_user',
        where: {
          whereType: 1,
          account_name: workNumber,
          mobile: phone,
        },
        filed: ['auserid'],
      })
      if (isRegister) {
        return {
          msg: '该账工号或手机号已经注册',
          code: 10201
        }
      }
      let create_userInfo = {};
      if (type == 'addUser') { // 添加管理员
        create_userInfo = await service.common.findOne({
          tableName: 'hd_admin_user',
          where: {
            auserid: userId
          }
        })
        if (!create_userInfo.account_name) {
          return {
            code: 10200,
            msg: '没有权限创建'
          }
        }
      }
      // console.log(passwd, create_userInfo.account_name,'----------------passwd')
      let is_default_passwd = 0; // 是否使用默认密码
      if (!passwd) {
        passwd = '123456';
      } else {
        is_default_passwd = 1
      }

      let encryRes = ctx.helper.aesEncrypt({
        data: passwd
      });
      // 在数据库插入一条记录
      await service.common.insertOne({
        tableName: 'hd_admin_user',
        params: {
          account_name: workNumber,
          real_name: `'${userName}'`,
          passwd: `'${encryRes.encryData}'`,
          passwd_salt: `'${encryRes.salt}'`,
          mobile: `'${phone}'`,
          aroleid,
          is_default_passwd,
          user_status: 1,
          create_by: create_userInfo.account_name || workNumber
        }
      })
      let userInfo = await service.common.findOne({
        tableName: 'hd_admin_user',
        where: {
          account_name: workNumber
        }
      });

      // 生成token
      if (type !== 'addUser') {// 注册时设置token
        await ctx.helper.getToken({
          userId: userInfo.auserid,
          userStatus: userInfo.user_status,
          roleType: userInfo.aroleid
        });
      }

      return {
        code: 10200,
        msg: '创建成功',
        data: {
          userName: userInfo.real_name,
          account: userInfo.account_name,
          roleType: userInfo.aroleid,
          phone: userInfo.mobile,
          userStatus: 1
        }
      }
    } catch (error) {
      console.log(error)
      return {
        code: 10500,
        msg: '注册失败'
      }
    }

  }


  // 修改
  async userUpDate(params) {
    const { ctx, service } = this;
    let {
      auserid,
      // userName,
      userId,
      phone,
      type,
      aroleid,
      userName,
      passwd
    } = params
    console.log('%c gc_type,=>: ', 'color: MidnightBlue; background: Aquamarine; font-size: 20px;', type, );

    try {
      // let encryRes = ctx.helper.aesEncrypt({
      //   data: passwd
      // });

      let u_userInfo = await service.common.findOne({
        tableName: 'hd_admin_user',
        where: {
          auserid: userId
        }
      })
      let param = {}
      if (type == "DEL") {
        param = {
          user_status: 2
        }
      } else if (type == 'reset') {
        let aesEncryptData = ctx.helper.aesEncrypt({ data: '123456' });
        param = {
          passwd: `'${aesEncryptData.encryData}'`,
          passwd_salt: `'${aesEncryptData.salt}'`
        }
        // console.log('%c gc_pwd=>: ', 'color: MidnightBlue; background: Aquamarine; font-size: 20px;', pwd);
      } else {
        param = {
          mobile: phone,
          aroleid: aroleid,
          update_by: u_userInfo.account_name,
          real_name: userName ? `'${userName}'` : null,
        };
        // if()

      }

      for (let key in param) {
        if (!param[key]) {
          delete param[key]
        }
      };
      let res = await service.common.upData({
        tableName: 'hd_admin_user',
        value: param,
        where: {
          auserid,
        }
      })
      return res ? { code: 10200, msg: '更新成功' } : { code: 10201, msg: '更新失败' }
    } catch (error) {
      console.log(error)
      return {
        code: 10500,
        msg: "更新失败"
      }
    }


  }

  async login({
    account,
    passwd,
    newPwd,
    operationType
  }) {
    const {
      ctx,
      app,
      service
    } = this;
    try {
      let userInfo = await service.common.findOne({
        tableName: 'hd_admin_user',
        where: {
          account_name: account
        }
      })
      if (!userInfo || !userInfo.auserid) {
        return {
          code: 10201,
          msg: '用户不存在！'
        }
      }
      if (userInfo.user_status == 0 || userInfo.user_status == 2) {
        return {
          code: 10201,
          msg: { 0: '没有权限登录', 2: '改用户已被删除！' }[userInfo.user_status]
        }
      }
      console.log(userInfo, 'userInfo----userInfo')
      let _pwd = ctx.helper.aesEncrypt({
        data: passwd,
        salt: userInfo.passwd_salt
      }).encryData;
      if (_pwd === userInfo.passwd) {
        // 生成token;
        if (operationType === 'modifyPwd') {
          let encryRes = ctx.helper.aesEncrypt({
            data: newPwd
          });
          await service.common.upData({
            tableName: 'hd_admin_user',
            value: {
              passwd: `'${encryRes.encryData}'`,
              passwd_salt: `'${encryRes.salt}'`,
            },
            where: {
              account_name: account
            }
          })
          return {
            code: 10200,
            msg: '密码设置成功'
          }
        }

        await ctx.helper.getToken({
          userId: userInfo.auserid,
          userStatus: userInfo.user_status,
          roleType: userInfo.aroleid
        });

        return {
          code: 10200,
          data: {
            userName: userInfo.real_name,
            account: userInfo.account_name,
            roleType: userInfo.aroleid,
            phone: userInfo.mobile,
            userStatus: 1
          },
          msg: '登录成功'
        }
      } else {
        return {
          code: 10201,
          msg: '密码错误',
        }
      }

    } catch (error) {
      console.log(error)
      return {
        code: 10500,
        msg: '登录失败',
      }
    }
  }




  async getMenuList(userId, tokenRoleType) {
    const {
      app,
      ctx,
      service
    } = this;
    try {
      let key = app.config.redisKey.adminPermissions;
      let baseRouter = {};
      let menus = await service.common.findAll({
        tableName: 'hd_admin_menus',
        where: `hidden=1 AND listorder > 0 ORDER BY listorder`
      })
      let adminPermissions = JSON.parse(await app.redis.get(key) || '{}')

      for (let item of menus) {
        let temp = {
          path: item.path,
          name: item.name,
          componentPath: item.component,
          meta: item.title,
          id: item.amenuid,
          component: item.component
        };
        if (item.redirect) {
          temp.redirect = {
            name: `${item.redirect}`
          }
        };
        adminPermissions[item.amenuid] ? temp.roleType = adminPermissions[item.amenuid] : ''
        console.log('---进来了---99999999999', temp.roleType, adminPermissions[item.amenuid], tokenRoleType, adminPermissions[item.amenuid])
        if (temp.roleType instanceof Array && temp.roleType.indexOf(String(tokenRoleType)) == -1) {
          console.log('---进来了---99999999999xxxxx', adminPermissions[item.amenuid].indexOf(String(tokenRoleType)), temp.roleType.indexOf(String(tokenRoleType) == -1))
          continue;
        }
        baseRouter[item.parentid] = !baseRouter[item.parentid] ? [temp] : baseRouter[item.parentid].concat([temp]);

        // routers[item.parentid] = temp
      }
      let routers = ctx.helper.formDataRouter(baseRouter);
      // console.log(routers,'--------router------')
      return {
        code: 10200,
        msg: 'success',
        data: routers
      }
    } catch (error) {
      console.log(error)
    }
  }

  /**
   * 添加一个路由
   */
  async menuAddMenu({
    name,
    component,
    path,
    redirect,
    parentid,
    meta,
    userId
  }) {
    // console.log('jjjjjjjjjjjj', name)
    const { ctx, service, logger } = this;
    try {
      let isRepeat = await service.common.findOne({
        tableName: 'hd_admin_menus',
        where: {
          whereType: 1,
          path: `'${path}'`,
          name: `'${name}'`
        }
      })
      if (isRepeat) {
        return {
          code: 10201,
          msg: '路由路径,或者名称重复！'
        }
      }

      let create_by_info = await service.common.findOne({
        tableName: 'hd_admin_user',
        where: {
          auserid: userId,
        },
        filed: [
          'account_name'
        ]
      });
      if (!create_by_info.account_name) {
        return {
          code: 10201,
          msg: '没有权限创建',
        }
      }
      let params = {
        title: `'${meta}'`,
        parentid: `'${parentid}'`,
        path: `'${path}'`,
        name: `'${name}'`,
        component: `'${component}'`,
        redirect: `'${redirect}'`,
        listorder: 1,
        create_by: create_by_info.account_name,
        update_by: create_by_info.account_name,
      }
      await service.common.insertOne({
        tableName: 'hd_admin_menus',
        params,
      });
      return {
        code: 10200,
        msg: '创建成功'
      }
    } catch (error) {
      console.log(error);
      logger.info(`菜单创建失败`);
      return {
        code: 10500,
        msg: '创建失败'
      }
    }

    // console.log('userid', ctx.request.body.userId)

    // await ctx.
    // console.log(isRepeat,'2934902384')
    // if()
  }
  async MenuModify(params) {
    let {
      name,
      component,
      path,
      redirect,
      meta,
      id,
      userId,
      aroleid,
    } = params
    const { ctx, service, logger } = this;
    try {
      let update_by_info = await service.common.findOne({
        tableName: 'hd_admin_user',
        where: {
          auserid: userId,
        },
        filed: [
          'account_name'
        ]
      });
      if (!update_by_info.account_name) {
        return {
          code: 10201,
          msg: '没有权限修改'
        }
      }
      let res = await service.common.upData({
        tableName: 'hd_admin_menus',
        value: {
          title: `'${meta}'`,
          path: `'${path}'`,
          name: `'${name}'`,
          component: `'${component}'`,
          redirect: `'${redirect}'`,
          update_by: update_by_info.account_name
        },
        where: {
          amenuid: id
        }
      })
      if (aroleid && aroleid.length) {
        await service.admin.user.setMenuPermissions(id, aroleid)
      }
      // if (res) {
      //   return {
      //     code:10200,
      //     msg:'更新成功'
      //   }
      // }else{

      // }
      return res ? { code: 10200, msg: '更新成功' } : { code: 10201, msg: '更新失败' }

    } catch (error) {
      console.log(error)
      logger.info(`菜单修改失败`);
      return {
        code: 10500,
        msg: '菜单修改失败'
      }
    }


  }
  /**
   *
   * @param {*} menuId  菜单id
   * @param {*} aroleid 角色id
   */
  async setMenuPermissions(menuId, aroleid) {
    const { ctx, app, service } = this;
    let key = app.config.redisKey.adminPermissions;
    let adminPermissions = JSON.parse(await app.redis.get(key) || '{}');
    adminPermissions[menuId] = aroleid
    await app.redis.set(key, JSON.stringify(adminPermissions));
  }
  /**
   *
   * @param {*} id  菜单id
   * @param {*} userId 修改人id，
   */
  async menuDelete({ id, userId }) {
    const { ctx, service, logger } = this;
    try {
      //
      let update_by_info = await service.common.findOne({
        tableName: 'hd_admin_user',
        where: {
          auserid: userId,
        },
        filed: [
          'account_name'
        ]
      });

      let res = await service.common.upData({
        tableName: 'hd_admin_menus',
        value: {
          hidden: 0,
          update_by: update_by_info.account_name

        },
        where: {
          whereType: 1,
          amenuid: id,
          parentid: id
        }
      })
      // if(res){
      //   return
      // }
      return res ? { code: 10200, msg: '删除成功' } : { code: 10201, msg: '删除失败' }

    } catch (error) {
      console.log(error);
      logger.log(`菜单删除失败`);
      return {
        code: 10500,
        msg: '删除成功'
      }
    }
  }
  async userList(param) {
    let { ctx, service, logger } = this, { userId, page, pageSize, userState, phone } = param;
    try {
      let limit = [(page - 1) * pageSize, pageSize]
      let sql = `
      SELECT
      hdu.account_name,
      hdu.real_name,
      hdu.mobile,
      hdu.aroleid,
      hdu.user_status,
      hdu.create_by,
      hdu.aroleid,
      hdu.auserid,
      hdr.role_name,
      DATE_FORMAT(
        hdu.create_time,
        '%Y/%m/%d:%H:%i:%S'
      ) AS c_time,
      hdu.update_by,
      DATE_FORMAT(
        hdu.update_time,
        '%Y/%m/%d:%H:%i:%S'
      ) AS u_time
    FROM
      hd_admin_user as hdu
    LEFT JOIN hd_admin_role as hdr ON  hdu.aroleid=hdr.aroleid`
      let where = `hdu.user_status = 1 AND hdu.aroleid > 1`;
      where = phone ? `${where} AND mobile=${phone}` : where;
      sql = `${sql} WHERE ${where} ORDER BY
      hdu.create_time DESC
      LIMIT ${ limit.join(',')}
      `
      let res = {}
      res.list = await service.common.findAll({ sql })

      res.total = (await service.common.findOne({
        tableName: 'hd_admin_user as hdu',
        where,
        filed: [`count(*) as totalNum`]

      })).totalNum

      res.roleList = await service.common.findAll({
        tableName: 'hd_admin_role',
        where: ` aroleid!=1 AND role_status=1`
      })

      return {
        code: 10200,
        data: res,
        msg: '请求成功'
      }
      console.log('%c gc_ userList=>: ', 'color: MidnightBlue; background: Aquamarine; font-size: 20px;', userList);

    } catch (error) {
      console.log(error, '--------')
      return {
        code: 10500,
        msg: '请求失败'
      }
    }
  }

  async roleTypeList(param) {
    const { ctx, service } = this;
    let res = {}, { userId, page, pageSize, role_name, aroleid, isAll } = param,
      limit = page && pageSize ? [(page - 1) * pageSize, pageSize] : null
    let where = [`role_status=1`];
    isAll ? '' : where.push(`aroleid>1`)
    role_name ? where.push(`role_name='${role_name}'`) : ''
    aroleid ? where.push(`aroleid=${aroleid}`) : ''
    res.list = await service.common.findAll({
      tableName: 'hd_admin_role',
      filed: ['aroleid', 'role_name', 'listorder', 'description', 'create_by', `DATE_FORMAT(create_time,'%Y/%m/%d:%H:%i:%S') as c_time`, `DATE_FORMAT(update_time,'%Y/%m/%d:%H:%i:%S') as u_time`, 'update_by',],
      where: ` ${where.join(' AND ')} ORDER BY create_time DESC ${limit ? `LIMIT ${limit.join(',')}` : ''}`
    })
    res.total = res.total = (await service.common.findOne({
      tableName: 'hd_admin_role',
      where: ` role_status=1 `,
      filed: [`count(*) as totalNum`]
    })).totalNum

    return {
      code: 10200,
      data: res,
      msg: 'success'
    }
  }


  async roleTypeUpData(param) {
    const { ctx, service } = this;
    let res = {}, { userId, aroleid, role_name, listorder, description, operationType } = param, _params = {}
    try {
      if (operationType == 'del') { // 删除操作
        _params.role_status = 2
      } else {
        _params = {
          update_by: userId,
          role_name: role_name ? `'${role_name}'` : null,
          listorder,
          description: description ? `'${description}'` : null
        }
      }

      for (let key in _params) {
        if (!_params[key]) {
          delete _params[key]
        }
      };
      await service.common.upData({
        tableName: 'hd_admin_role',
        value: _params,
        where: {
          aroleid
        }
      })

      return {
        code: 10200,
        msg: '操作成功'
      }
    } catch (error) {
      console.log(error)
      return {
        code: 10500,
        msg: '服务器异常'
      }
    }

  }



  async addRoleType(param) {
    const { ctx, service } = this;
    let res = {}, { userId, role_name, listorder, description } = param;
    try {
      let _params = {
        role_name: `'${role_name}'`,
        listorder: listorder ? listorder : null,
        description: description ? `'${description}'` : '',
        create_by: userId,
        role_status: 1,
        update_by: userId
      }

      await service.common.insertOne({
        tableName: 'hd_admin_role',
        params: _params
      })

      return {
        code: 10200,
        msg: '创建成功'
      }
    } catch (error) {
      console.log(error)
      return {
        code: 10500,
        msg: '服务器异常'
      }
    }
  }

}